<template>
  <a-modal class="common-modal" :title="$t('other.batchEditTargetYield')" :footer="null" :width="720" :visible="visible" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <div class="common-modal-content">
        <div class="blue-line mb-15">{{ $t('other.dailyProdDetail') }}</div>
        <TimeTableForm ref="timeTableFormRef" v-if="visible" :tableData="tableData" />
      </div>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{ $t('common.ok') }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup>
import { nextTick, ref } from 'vue'
import TimeTableForm from './timeTableForm.vue'
import axios from '@/utils/request'
import { message } from 'ant-design-vue'
import i18n from '@/locales/index'

const { t } = i18n.global
const emits = defineEmits(['ok'])
let visible = ref(false)
let confirmLoading = ref(false)
let recordIds = ref([])
let tableData = ref([])
const timeTableFormRef = ref()

const initModalData = () => {
  tableData.value = [{ timeRange: [], targetYield: 0, id: Math.random() }]
}
const open = async (idList) => {
  recordIds.value = idList
  initModalData()
  visible.value = true
  await nextTick()
}
const getParams = () => {
  let params = {
    yieldTargetIds: recordIds.value
  }
  let data = timeTableFormRef.value.dataSource
  params.targetDetailList = data.map(i => {
    let { targetYield, timeRange } = i
    return {
      endTime: timeRange[1],
      startTime: timeRange[0],
      quantity: targetYield
    }
  })
  return params
}
const handleOk = async () => {
  try {
    await timeTableFormRef.value.timeRef.validateFields()
    confirmLoading.value = true
    let params = getParams()
    const res = await axios.postAction('/api/hanger/yield-target/update-batch', params)
    if (res.success) {
      message.success(res.msg || t('common.doSuccess'))
      handleCancel()
      emits('ok')
    }
  } catch (err) {
    confirmLoading.value = false
  }
}
const handleCancel = () => {
  visible.value = false
  confirmLoading.value = false
  tableData.value = []
  visible.value = false
}

defineExpose({
  open
})
</script>
